// 注意：此文件需要在安装gRPC后编译
// 编译前请确保已安装gRPC和protobuf库

#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <chrono>
#include <queue>
#include <mutex>
#include <condition_variable>

// gRPC头文件 - 编译时会自动找到正确路径
#include <grpcpp/grpcpp.h>
#include "chat.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReaderWriter;
using grpc::Status;
using chat::ChatMessage;
using chat::ChatService;

class ChatServiceImpl final : public ChatService::Service {
public:
    Status Chat(ServerContext* context,
                ServerReaderWriter<ChatMessage, ChatMessage>* stream) override {
        std::cout << "chat客户端连接建立" << std::endl;
        
        // 解析ServerContext中的客户端信息
        std::cout << "=== 客户端连接信息 ===" << std::endl;
        
        // 1. 获取客户端地址
        std::string peer = context->peer();
        std::cout << "客户端地址: " << peer << std::endl;
        
        
        // 2. 获取认证信息 (如果有的话)
        auto auth_context = context->auth_context();
        if (auth_context) {
            //std::cout << "认证类型: " << auth_context->GetPeerIdentityPropertyName() << std::endl;
        } else {
            //std::cout << "无认证信息 (不安全连接)" << std::endl;
        }
        
        // 3. 获取客户端发送的元数据 (metadata/headers)
        auto client_metadata = context->client_metadata();
        std::cout << "客户端元数据数量: " << client_metadata.size() << std::endl;
        for (auto it = client_metadata.begin(); it != client_metadata.end(); ++it) {
            std::cout << "  " << std::string(it->first.data(), it->first.length()) 
                    << ": " << std::string(it->second.data(), it->second.length()) << std::endl;
        }
        
        // 4. 检查是否被取消
        if (context->IsCancelled()) {
            std::cout << "请求已被客户端取消" << std::endl;
            return Status::CANCELLED;
        }
        
        // 5. 获取截止时间
        auto deadline = context->deadline();
        auto now = std::chrono::system_clock::now();
        if (deadline != std::chrono::system_clock::time_point::max()) {
            auto time_left = std::chrono::duration_cast<std::chrono::seconds>(deadline - now).count();
            std::cout << "请求截止时间还剩: " << time_left << " 秒" << std::endl;
        } else {
            std::cout << "请求无截止时间限制" << std::endl;
        }
        
        // 6. 设置服务器端元数据 (可选)
        context->AddInitialMetadata("server-version", "1.0.0");
        context->AddInitialMetadata("server-timestamp", std::to_string(
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::system_clock::now().time_since_epoch()).count()));
        
        std::cout << "========================" << std::endl;
        
        // 用于存储接收到的消息
        std::queue<ChatMessage> message_queue;
        std::mutex queue_mutex;
        std::condition_variable cv;
        bool finished = false;
        
        // 启动一个线程来读取客户端消息
        std::thread reader_thread([&]() {
            ChatMessage message;
            while (stream->Read(&message)) {
                std::cout << "收到消息 [" << message.user() << "]: " 
                        << message.message() << std::endl;
                
                // 将消息放入队列，供写线程处理
                {
                    std::lock_guard<std::mutex> lock(queue_mutex);
                    message_queue.push(message);
                }
                cv.notify_one();
            }
            finished = true;
            cv.notify_one();
            std::cout << "客户端断开连接" << std::endl;
        });
        
        // 主线程处理写操作
        int server_message_count = 0;
        while (!finished || !message_queue.empty()) {
            std::unique_lock<std::mutex> lock(queue_mutex);
            cv.wait(lock, [&] { return !message_queue.empty() || finished; });
            
            // 处理队列中的消息
            while (!message_queue.empty()) {
                ChatMessage received_msg = message_queue.front();
                message_queue.pop();
                lock.unlock();
                
                // 回复消息
                ChatMessage reply;
                reply.set_user("Server");
                reply.set_message("服务器收到: " + received_msg.message());
                reply.set_timestamp(std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::system_clock::now().time_since_epoch()).count());
                
                if (!stream->Write(reply)) {
                    std::cout << "写入失败，客户端可能已断开" << std::endl;
                    finished = true;
                    break;
                }
                
                lock.lock();
            }
            
            // 定期发送服务器主动消息
            if (!finished && server_message_count < 3) {
                lock.unlock();
                std::this_thread::sleep_for(std::chrono::seconds(5));
                
                ChatMessage server_msg;
                server_msg.set_user("Server");
                server_msg.set_message("服务器推送消息 #" + std::to_string(++server_message_count));
                server_msg.set_timestamp(std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::system_clock::now().time_since_epoch()).count());
                
                if (!stream->Write(server_msg)) {
                    std::cout << "写入失败，客户端可能已断开" << std::endl;
                    finished = true;
                }
                lock.lock();
            }
        }
        
        reader_thread.join();
        return Status::OK;
    }
};

void RunServer() {
    std::string server_address("0.0.0.0:8080");
    ChatServiceImpl service;
    
    ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "C++服务器启动，监听地址: " << server_address << std::endl;
    std::cout << "等待客户端连接... " << std::endl;

    server->Wait();
}

int main(int argc, char** argv) {
    RunServer();
    return 0;
}